package org.southyin.springboot02.controller;

import org.southyin.springboot02.commons.CommonsResp;
import org.southyin.springboot02.model.CmsCustomer;
import org.southyin.springboot02.service.CmsCustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
@CrossOrigin(value = "http://127.0.0.1:5500",allowCredentials = "true")
public class CustomerController {
    @Autowired
    CmsCustomerService service;
    @PostMapping("/reg")
    public CommonsResp reg(CmsCustomer cmsCustomer) {
        CommonsResp commonsResp = null;
        if (cmsCustomer.getEmail() == null || cmsCustomer.getEmail().trim().equals("") || cmsCustomer.getPassword() == null || cmsCustomer.getPassword().trim().equals("")) {
            commonsResp = CommonsResp.failed(400,"邮箱或密码不能为空");
        }
        else{
            commonsResp = service.customerReg(cmsCustomer);
        }
        return commonsResp;
    }

    @PostMapping("/doLogin")
    public CommonsResp doLogin(CmsCustomer cmsCustomer, HttpSession session) {
        CommonsResp commonsResp = null;
        if (cmsCustomer.getEmail() == null || cmsCustomer.getEmail().trim().equals("") || cmsCustomer.getPassword() == null || cmsCustomer.getPassword().trim().equals("")) {
            commonsResp = CommonsResp.failed(400,"邮箱或密码不能为空");
        }
        else{
            commonsResp = service.customerLogin(cmsCustomer);
            if (commonsResp.getData() != null) {
                // 获取Session，保存登录者信息
                session.setAttribute("loginer",commonsResp.getData());
            }
        }
        return commonsResp;
    }

    @GetMapping("/logout")
    public CommonsResp logout(HttpSession session) {
        session.invalidate();
        return CommonsResp.succeess(200, "退出成功");
    }

    @GetMapping("/personal")
    public CmsCustomer personal(Long authorId) {
       return service.getPersonInfos(authorId);
    }
}
